// pages/index_detail/index_detail.js
const app = getApp();
import common from "../../util/common";
let id, index;
Page({

  data: {
    detail: {},
    loading: true,
    isDark:false
  },

  onLoad: function (options) {
    id = options.id;
    index = options.index;
    this.getDetail();
    this.setData({
      isDark:app.globalData.isDark
    })
  },

  // 点赞按钮
  clickLike() {
    this.pushData()

  },
  //把点赞发送到数据库
  pushData() {

    let onlike = this.data.detail.onlike;
    let zanSize = this.data.detail.zanSize;
    let userArr = this.data.detail.userArr;
    if (onlike) {
      zanSize--
      userArr.forEach((item, index) => {
        if (item.avatarUrl == app.globalData.userInfo.avatarUrl) {
          userArr.splice(index, 1)
        }
      })
    } else {
      zanSize++
      userArr.push({
        avatarUrl: app.globalData.userInfo.avatarUrl
      })
      if (userArr.length >= 5) {
        userArr = userArr.slice(1, 6)
      }
    }
    this.setData({
      "detail.onlike": !onlike,
      "detail.zanSize": zanSize,
      "detail.userArr": userArr
    })

    let posttime = Date.now();
    wx.cloud.callFunction({
      name: "article_like_add",
      data: {
        nickName: app.globalData.userInfo.nickName,
        avatarUrl: app.globalData.userInfo.avatarUrl,
        posttime,
        artid: id,
        title: this.data.detail.title
      }
    }).then(res => {
      console.log(res);
    })
  },

  getDetail() {
    wx.cloud.callFunction({
      name: 'article_list_get_one',
      data: {
        id
      }
    }).then(res => {
      let item = res.result.data;
      let hits = item.hits ? item.hits : 0;
      item.hits = common.getNumber(hits);
      item._createTime = common.getTime(item._createTime, 4);


      res.result.data.content =
        res.result.data.content.replace(/<img/ig, "<img style='max-width:100%'");

      this.setData({
        detail: res.result.data,
        loading: false
      })
      console.log(res.result.data)
    })
  },
  //生命周期函数--监听页面卸载
  //即关闭该页面时进行功能实现
  onUnload: function () {
    let pages = getCurrentPages()[getCurrentPages().length - 2]; //在详情页回退到首页
    let listArr = pages.data.listArr;
    listArr[index].zanSize = this.data.detail.zanSize; //设置资讯页首页与详情页的点赞数同步
    pages.setData({
      listArr
    })
  }

})